# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2005-2006 CamptoCamp
# Copyright (c) 2006-2010 OpenERP S.A
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import time, os
from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp.report import report_sxw
import locale
from openerp.tools import float_round, float_is_zero, float_compare
locale.setlocale(locale.LC_ALL, '')

class summary_project_contract_report(report_sxw.rml_parse):
    _name = 'summary.project.contract.report'

    def _search_data(self, cr, uid, ids, data_obj, val_data, filter_selection, default_from, default_to, input_from, input_to, selection_ids, context=None):
        data_header = ''
        data_ids = []

        if context is None:
            context = {}
        
        if filter_selection == 'all_vall':
            data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'def':
            data_found = False
            if default_from and data_obj.browse(cr, uid, default_from) and data_obj.browse(cr, uid, default_from).name:
                default_from_header = data_obj.browse(cr, uid, default_from).name
                data_found = True
                val_data.append(('name', '>=', default_from_header))
            if default_to and data_obj.browse(cr, uid, default_to) and data_obj.browse(cr, uid, default_to).name:
                default_to_header = data_obj.browse(cr, uid, default_to).name
                data_found = True
                val_data.append(('name', '<=', default_to_header))
            if data_found:
                data_header = '"' + default_from_header + '" - "' + default_to_header + '"'
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'input':
            data_found = False
            if input_from:
                data_ids_from = data_obj.search(cr, uid, [('name','=ilike', input_from + '%')], order="name", limit=1)
                if data_ids_from:
                    input_from_name = data_obj.browse(cr, uid, data_ids_from[0]).name
                    data_found = True
                    val_data.append(('name', '>=', input_from_name))
            if input_to:
                data_ids_to = data_obj.search(cr, uid, [('name','=ilike', input_to + '%')], order="name desc", limit=1)
                if data_ids_to:
                    input_to_name = data_obj.browse(cr, uid, data_ids_to[0]).name
                    data_found = True
                    val_data.append(('name', '<=', input_to_name))
            data_header = '"' + input_from + '" - "' + input_to + '"'
            if data_found:
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'selection':
            if selection_ids:
                sel_ids = ''
                for sel in  data_obj.browse(cr, uid, selection_ids):
                    sel_ids += ('"%s",')%(sel.name,)

                data_header = '[' + sel_ids +']'
                data_ids = selection_ids
                
        return data_header, data_ids
    
    def set_context(self, objects, data, ids, context=None):
        new_ids = ids
        
        if context is None:
            context = {}
             
        self.filter_selection = data['form']['filter_selection'] or False
        self.cust_filter_selection = data['form']['cust_filter_selection'] or False
        self.date_selection = data['form']['date_selection'] or False
        self.curr_filter_selection = data['form']['curr_filter_selection'] or False 
        self.sortby_ids = data['form']['sortby_ids'] or False 
        self.output_project_header, self.project_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('project.project'),
                                                                                      [('state','!=','cancelled')],
                                                                                      data['form']['filter_selection'],
                                                                                      data['form']['project_default_from'] and data['form']['project_default_from'][0] or False,
                                                                                      data['form']['project_default_to'] and data['form']['project_default_to'][0] or False,
                                                                                      data['form']['project_input_from'] or False,
                                                                                      data['form']['project_input_to'] or False,
                                                                                      data['form']['project_name_ids'] or False,
                                                                                      context=context)
        
        self.output_cust_header, self.cust_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('res.partner'),
                                                                                      [],
                                                                                      data['form']['cust_filter_selection'],
                                                                                      data['form']['cust_name_def_from'] or False,
                                                                                      data['form']['cust_name_def_to'] or False,
                                                                                      data['form']['cust_name_input_from'] or False,
                                                                                      data['form']['cust_name_input_to'] or False,
                                                                                      data['form']['partner_ids'] or False,
                                                                                      context=context)
        
        date_from = data['form']['date_from']
        date_to = data['form']['date_to']
        
        output_date_header = ''
        val_date = []
        if data['form']['date_selection'] == 'date_sel':
            if date_from and not date_to:
                output_date_header = 'Date Start From : %s' % (date_from,)
                val_date.append(('date_start','>=',str(date_from)))
            elif date_to and not date_from:
                output_date_header = 'Date Until : %s' % (date_to,)
                val_date.append(('date_start','<=',str(date_to))) 
            elif date_to and date_from:
                output_date_header = 'Date Start From : %s, Until: %s' % (date_from, date_to)
                val_date.append(('date_start','>=',str(date_from)))
                val_date.append(('date_start','<=',str(date_to)))

        self.output_date_header = output_date_header
        self.val_date = val_date
        
        return super(summary_project_contract_report, self).set_context(objects, data, new_ids)

    def __init__(self, cr, uid, name, context=None):
        super(summary_project_contract_report, self).__init__(cr, uid, name, context=context)
        self.balance_by_cur = {}
        self.localcontext.update({
            'time': time,
            'locale': locale,
            'get_printed_date' : self._get_printed_date,
            'get_printed_by': self._get_printed_by,
            'get_output_project_header': self._get_output_project_header,
            'get_output_customer_header': self._get_output_customer_header,
#             'get_output_currency_header': self._get_output_currency_header, 
            'get_output_date_header': self._get_output_date_header, 
            'get_output_sortby_header': self._get_output_sortby_header,
            'get_balance_by_cur': self._get_balance_by_cur,
            'get_lines': self._get_lines,
            'get_decimal_accuracy_account': self._get_decimal_accuracy_account,
            })
    
    def _get_printed_date(self):
        header = ''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            tz = user_obj.browse(self.cr, self.uid, user_ids[0])
            tz_name = tz.tz
        os.environ['TZ'] = tz_name
        time.tzset()
        header = 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S")
         
        return header
    
    def _get_printed_by(self):
        header =''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            user_id = user_obj.browse(self.cr, self.uid, user_ids[0])
            user_name = user_id.name
        
        header = 'Printed by : ' + user_name
        
        return header
    
    def _get_output_project_header(self):
        header = ''
        if self.output_project_header:
            header = 'Project : ' + self.output_project_header
         
        return header
    
    def _get_output_customer_header(self):
        header = ''
        if self.output_cust_header:
            header = 'Customer : ' + self.output_cust_header
         
        return header
    
    def _get_output_currency_header(self):
        header = ''
        if self.output_curr_header:
            header = 'Currency : ' + self.output_curr_header
         
        return header
     
    def _get_output_date_header(self):
        header = ''
        if self.output_date_header:
            header = self.output_date_header
         
        return header
    
    def _get_balance_by_cur(self):
        result = []
        currency_obj    = self.pool.get('res.currency')
         
        for item in self.balance_by_cur.items():
            result.append({
                'cur_name' : currency_obj.browse(self.cr, self.uid, item[0]).name,
                'quote_amt' : item[1]['quote_amt'],
                'inv_amt' : item[1]['inv_amt'],
                'inv_amt_home' : item[1]['inv_amt_home'],
                'profit_loss' : item[1]['profit_loss'],
            })
        result = result and sorted(result, key=lambda val_res: val_res['cur_name']) or []
        return result
     
    def _get_output_sortby_header(self):
        header = output_sortby_header = ''
        result = []
        
        summary_contract_sortby_ids =""
        if self.sortby_ids:
            summary_contract_sortby_ids = self.pool.get('summary.project.contract.sortby').search(self.cr, self.uid, [('id', 'in', self.sortby_ids)], order='seq desc')
        
        if summary_contract_sortby_ids:
            for item in self.pool.get('summary.project.contract.sortby').browse(self.cr, self.uid, summary_contract_sortby_ids):
                result.append({
                        'seq' : item['seq'],
                        'sort_by' : item['sort_by'],
                        })
            result = result and sorted(result, key=lambda val_res: val_res['seq']) or []               
            
            for rs in result:
                sort_name = ''
                if rs['sort_by'] == 'project_name':
                    sort_name = 'Project'
                elif rs['sort_by'] == 'cust_name':
                    sort_name = 'Customer'
                elif rs['sort_by'] == 'date_project':
                    sort_name = 'Date'
                elif rs['sort_by'] == 'currency':
                    sort_name = 'Currency'
                elif rs['sort_by'] == 'status':
                    sort_name = 'Status' 
                output_sortby_header += ('"%s",')%(sort_name,)
            header = 'Sort By : ' + output_sortby_header

        return header
    
    def _get_decimal_accuracy_account(self):
        dp = 2
        dp_obj = self.pool.get('decimal.precision')
        dp_ids = dp_obj.search(self.cr, self.uid, [('name','=','Account')])
        if dp_ids :
            dp_id = dp_obj.browse(self.cr, self.uid, dp_ids[0])
            dp = dp_id.digits
        return dp
    
    def _get_lines(self):
        cr  = self.cr
        uid = self.uid
        
        project_project_obj = self.pool.get('project.project')
        summary_project_contract_sortby_obj = self.pool.get('summary.project.contract.sortby') 

        results     = []
        val_project = [] 
        result_curr = []
         
        project_ids = self.project_ids
        cust_ids = self.cust_ids  
        output_sortby_header = ''
        
        if project_ids:
            val_project.append(('id','in',project_ids))
        if cust_ids:
            val_project.append(('partner_id','in',cust_ids))
        if self.val_date:
            val_project += self.val_date
        
        summary_contract_sortby_ids = []
        if self.sortby_ids:
            summary_contract_sortby_ids = summary_project_contract_sortby_obj.search(cr, uid, [('id', 'in', self.sortby_ids)], order='seq desc')
            
        summary_project_contract_ids = project_project_obj.search(cr, uid, val_project)
        if summary_project_contract_ids:
              
            for spc in project_project_obj.browse(cr, uid, summary_project_contract_ids):
                bill_type = ''
                cur_id_part = False
                cur_id_part = spc.currency_id.id
                
                bill_type = 'Actual' if spc.billing_type == 'bill' else 'Non Actual'
                          
                results.append({
                    'billing_type' : bill_type,
                    'date_spc' : spc.date_start,
                    'project_name' : spc.name,
                    'cust_name' : spc.partner_id.name,
                    'planned_normal_hours' : spc.sy_normal_qty + spc.mech_normal_qty + spc.elec_normal_qty + 
                                    spc.weld_normal_qty + spc.int_normal_qty + spc.desg_normal_qty + 
                                    spc.dept1_normal_qty + spc.dept2_normal_qty + spc.dept3_normal_qty ,
                    'planned_ot_hours' : spc.sy_ot_qty + spc.mech_ot_qty + spc.elec_ot_qty + 
                                    spc.weld_ot_qty + spc.int_ot_qty + spc.desg_ot_qty + 
                                    spc.dept1_ot_qty + spc.dept2_ot_qty + spc.dept3_ot_qty ,
                    'actual_normal_hours' : spc.sy_actual_normal_hours + spc.mech_actual_normal_hours + spc.elec_actual_normal_hours + 
                                    spc.weld_actual_normal_hours + spc.int_actual_normal_hours + spc.desg_actual_normal_hours + 
                                    spc.dept1_actual_normal_hours + spc.dept2_actual_normal_hours + spc.dept3_actual_normal_hours ,
                    'actual_ot_hours' :  spc.sy_actual_ot_hours + spc.mech_actual_ot_hours + spc.elec_actual_ot_hours + 
                                    spc.weld_actual_ot_hours + spc.int_actual_ot_hours + spc.desg_actual_ot_hours + 
                                    spc.dept1_actual_ot_hours + spc.dept2_actual_ot_hours + spc.dept3_actual_ot_hours ,
                    'curr_name' : spc.currency_id.name,
                    'quote_amt' : spc.amount_total or 0,
                    'inv_amt' : spc.inv_amount_total or 0,
                    'inv_amt_home' : spc.inv_amount_home_total or 0,
                    'profit_loss' : spc.inv_amount_home_total - spc.amount_cost_total or 0,
                    'state' : spc.state,
                })
                if cur_id_part not in self.balance_by_cur:
                    self.balance_by_cur.update({cur_id_part : {
                             'quote_amt' : spc.amount_total or 0,
                             'inv_amt' : spc.inv_amount_total or 0,
                             'inv_amt_home' : spc.inv_amount_home_total or 0,
                             'profit_loss' : spc.inv_amount_home_total - spc.amount_cost_total or 0,
                             }
                        })
                else:
                    res_currency_grouping = self.balance_by_cur[cur_id_part].copy()
                    res_currency_grouping['quote_amt'] += spc.amount_total
                    res_currency_grouping['inv_amt'] +=  spc.inv_amount_total
                    res_currency_grouping['inv_amt_home'] += spc.inv_amount_home_total
                    res_currency_grouping['profit_loss'] += spc.inv_amount_home_total - spc.amount_cost_total
                    self.balance_by_cur[cur_id_part] = res_currency_grouping
              
            if summary_contract_sortby_ids:
                for summary_contract_sortby in summary_project_contract_sortby_obj.browse(cr, uid, summary_contract_sortby_ids):
                    results = results and sorted(results, key=lambda val_res: val_res[summary_contract_sortby.sort_by]) or []               
            else:
                results = results and sorted(results, key=lambda val_res: val_res['state']) or []
                results = results and sorted(results, key=lambda val_res: val_res['curr_name']) or []
                results = results and sorted(results, key=lambda val_res: val_res['cust_name']) or []
                results = results and sorted(results, key=lambda val_res: val_res['project_name']) or []
                results = results and sorted(results, key=lambda val_res: val_res['date_spc']) or []
          
        return results
        
report_sxw.report_sxw('report.summary.project.contract.report_landscape', 'param.summary.project.contract.report',
    'addons/batam_fast_module/project/report/report/summary_project_contract_report.rml', parser=summary_project_contract_report, header=False)
